package com.apexedu.identity.service.impl;

import com.apexedu.biz.entity.TServiceCode;
import com.apexedu.biz.entity.TServiceCodesort;
import com.apexedu.biz.entity.TServiceIntroducd;
import com.apexedu.biz.entity.TServiceMenu;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.action.IdLoginAction;
import com.apexedu.identity.action.IdMenuAction;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.service.IdMenuService;
import com.apexedu.portal.constant.Constants;
import com.apexedu.support.cache.CacheUtils;
import com.apexedu.sys.SysConstant;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.json.JsonUtil;
import net.ysen.tree.entitybean.TreeNode;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.*;

public class IdMenuServiceImpl extends AbstractBaseServiceSupport implements IdMenuService {

    private Map<String, String> imgeMap = new HashMap<String, String>();

    public List<?> list(Object myaction, Pager pager) throws Exception {

        IdMenuAction action = (IdMenuAction) myaction;
        action.getRequest().setAttribute("showCheckBox", action.getParameter("showCheckBox"));
        // 采用控件展示树，数据给控件去取，这里直接转向过去
        return null;
    }

    @Override
    public void openCreate(Object myaction) throws Exception {
        IdMenuAction action = (IdMenuAction) myaction;
        List<String> listIcon = new ArrayList<String>();
//      File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator + "images" + File.separator + "shd" + File.separator + "icons");
//        File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator +  "images" + File.separator + "shd" + File.separator + "newicons");
//        for (File f : file.listFiles()) {
//            listIcon.add(f.getName());
//            imgeMap.put(f.getName(),f.getName());
//        }
        File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator + "images" + File.separator + "shd" + File.separator + "icons");
        for (File f : file.listFiles()) {
            if (imgeMap.get(f.getName())==null){
                listIcon.add(f.getName());
            }
        }
        action.setListIcon(listIcon);
        if (true||Constants.ProjectInfo.PROJECT_CODE.equals("shd")) {
            //装载服务类别
            loadService(action, "");
        }
        
        action.setProjectCode(Constants.ProjectInfo.PROJECT_CODE);
    }

    public void load(Object myaction) throws Exception {

        IdMenuAction action = (IdMenuAction) myaction;
        String menuid = action.getParameter("wid");
        TServiceCodesort tservicecodesort=null;
        StringBuffer sb_mene=new StringBuffer();
        TSysMenu tsysMenu = getBaseDao().findById(TSysMenu.class, menuid);

        String fwsyfl = getBaseDao().findFieldValue("select upmenuid from TSysMenu a where a.belongtoapp=? and a.bizcode=? and a.oldbelongtoapp=?",
                ConfigUtil.getString("portalCode"), tsysMenu.getBizcode(), tsysMenu.getBelongtoapp());
        if (StringUtil.isNotBlank(fwsyfl))
            tsysMenu.setFwsyfl(fwsyfl);

        action.setTsysMenu(tsysMenu);

        //图标库集合
        List<String> listIcon = new ArrayList<String>();

//      File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator + "images" + File.separator + "shd" + File.separator + "icons");
//        File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator +  "images" + File.separator + "shd" + File.separator + "newicons");
//        for (File f : file.listFiles()) {
//            listIcon.add(f.getName());
//            imgeMap.put(f.getName(), f.getName());
//        }
        File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator + "images" + File.separator + "shd" + File.separator + "icons");
        for (File f : file.listFiles()) {
            if (imgeMap.get(f.getName())==null){
                listIcon.add(f.getName());
            }
        }
        action.setListIcon(listIcon);
        if (true||Constants.ProjectInfo.PROJECT_CODE.equals("shd")) {
            //装载服务类别
            loadService(action, tsysMenu.getMenuid());
            loadServicedescribe(action, tsysMenu.getMenuid());
        }
        //装载服务描述
        
        action.setProjectCode(Constants.ProjectInfo.PROJECT_CODE);
    }

    /**
     * 支持传统的页面提交方式删除菜单
     */
    public boolean remove(Object myaction) throws Exception {
        //清除资源树缓存数据
        CacheUtils.delete("ZYTreeJsonData");

        IdMenuAction action = (IdMenuAction) myaction;
        String menuid = action.getParameter("menuid");
        boolean deleteSuccess = removeMenuRelation(menuid);
        if (deleteSuccess) {
            BusinessLogUtil.log(action.getLoginuser().getUserloginid(), SysConstant.CZDX_T_SYS_MENU,
                    SysConstant.LOG_ACTION_DEL, IdLoginAction.getIpAddr(action.getRequest()));
        }
        return deleteSuccess;
    }

    private boolean removeMenuRelation(String menuid) throws Exception {
        removeUserUseMenu(menuid);
        removeRoleUseMenuButton(menuid);
        removeRoleUseMenu(menuid);
        removeFwDy(menuid); //删除用户订阅的服务资源
        return getBaseDao().deleteAll("TSysMenu", "menuid", "like", menuid);
    }

    private boolean removeUserUseMenu(String menuid) throws Exception {

        return getBaseDao().deleteAll("TSysUserMenu", "menuid", "like", menuid);
    }

    private boolean removeRoleUseMenu(String menuid) throws Exception {

        return getBaseDao().deleteAll("TSysRoleMenu", "menuid", "like", menuid);
    }

    private boolean removeRoleUseMenuButton(String menuid) throws Exception {

        return getBaseDao().deleteAll("TSysRoleMenuButton", "menuid", "like", menuid);
    }

    /**
     * 删除用户订阅的服务资源
     *
     * @param menuid
     * @return
     * @throws Exception
     */
    private boolean removeFwDy(String menuid) throws Exception {
        return DBUtil.executeSQL("delete from t_fw_dy where menuid = ?", menuid) > 0;
    }

    /**
     * 添加系统到门户资源下
     */
    public void addPortal(TSysMenu menu) throws Exception {
        String menuid = menu.getMenuid();
        String fwsyfl = menu.getFwsyfl();
        String myNewNodeId = getNewMenuIdByParentMenuId(fwsyfl);//新增服务id
        menu = getBaseDao().findById(TSysMenu.class, menuid);
        baseDao.update(menu);//修改是否添加到门户状态

        String menupath = (String) DBUtil.queryFieldValue("select appurl from t_access_app_reg t where t.appid = ?", menu.getBelongtoapp());
        menu.setMenupath(menupath + "/UIProcessor?Table=" + menu.getMenupath() + "&PageOnly=true");
        menu.setUpmenuid(fwsyfl);
        menu.setOldbelongtoapp(menu.getBelongtoapp());
        menu.setBelongtoapp(ConfigUtil.getString("portalCode"));
        menu.setMenuid(myNewNodeId);
        menu.setBizcode(menu.getBizcode()); //关联原数据的menuid
        baseDao.save(menu);//添加一条服务记录

        //配置的角色权限也复制过来
        DBUtil.executeSQL("insert into t_sys_role_menu(id,roleid,menuid)" +
                " select to_char(sysdate,'yyyyMMddHH24missSSS')||rownum,roleid,?" +
                " from t_sys_role_menu where menuid = ?", myNewNodeId, menuid);
    }

    @Override
    public String getMenus() throws Exception {
        String sql = "select t.menuid as id,t.menuname as text,upmenuid as parentid from t_sys_menu t where t.belongtoapp not in (?,?) and t.state='1'" +
                " and exists (select null from t_access_app_reg a where a.appid=t.belongtoapp and a.state='1')" +
                " and not exists (select null from t_sys_menu b where b.bizcode=t.bizcode and b.oldbelongtoapp=t.belongtoapp and b.belongtoapp=?)" +
                " order by ordernum desc";
        String portalid = ConfigUtil.getString("portalCode");
        List<TreeNode> list = DBUtil.queryAllBeanList(sql, TreeNode.class, portalid, ConfigUtil.getString("AuCenterAccessEnterCode"), portalid);
        TreeNode root = new TreeNode();
        root.setId("000");
        root.setParentid("");
        root.setText("资源管理中心");
        root.setChildCount(list.size());
        root.setValue("000");
        list.add(0, root);
        List<TreeNode> listRemove = new ArrayList<TreeNode>(); //删除多余数据 如父节点被禁用
        for (TreeNode node : list) {
            if (!"000".equals(node.getId())) {
                boolean succ = false;
                for (TreeNode nodeS : list) {
                    if (node.getParentid().equals(nodeS.getId())) {
                        succ = true;
                        break;
                    }
                }
                if (!succ) {
                    listRemove.add(node);
                }
            }
        }
        list.removeAll(listRemove);
        String jsonStr = JsonUtil.getJSONString(list);
        return jsonStr;
    }

    /**
     * 批量添加服务
     *
     * @param menuids
     * @param upmenuid
     * @throws Exception
     */
    @Override
    public void saveBatchService(String menuids, String upmenuid) throws Exception {
        List<TSysMenu> adds = new ArrayList<TSysMenu>();//新增门户服务

        if (StringUtils.isNotBlank(menuids) && StringUtils.isNotBlank(upmenuid)) {
            String myNewNodeId = getNewMenuIdByParentMenuId(upmenuid);//新增服务id
            List<TSysMenu> menuList = DBUtil.queryAllBeanList("select t.*,a.appurl from t_sys_menu t left join t_access_app_reg a on t.belongtoapp=a.appid" +
                    " where menuid in ('" + menuids.replaceAll(",", "','") + "')", TSysMenu.class);
            int i = 0;
            for (TSysMenu menu : menuList) {
                TSysMenu newmenu = new TSysMenu();
                //TODO
                newmenu.setMenupath(menu.getAppurl() + "/UIProcessor?Table=" + menu.getMenupath() + "&PageOnly=true");
                newmenu.setUpmenuid(upmenuid);
                newmenu.setBelongtoapp(ConfigUtil.getString("portalCode"));
                String wid = joinId(myNewNodeId, i++);
                newmenu.setMenuid(wid);
                newmenu.setBizcode(menu.getBizcode());
                newmenu.setOldbelongtoapp(menu.getBelongtoapp());
                newmenu.setMenuname(menu.getMenuname());
                newmenu.setDepth(menu.getDepth());
                newmenu.setState(menu.getState());
                newmenu.setOrdernum(menu.getOrdernum());
                newmenu.setSrctype(menu.getSrctype());
                newmenu.setIsshare(menu.getIsshare());
                adds.add(newmenu);
            }
        }
        baseDao.saveAll(adds);
        //配置的角色权限也复制过来
        DBUtil.executeSQL("insert into t_sys_role_menu(id,roleid,menuid)" +
                        " select to_char(sysdate,'yyyyMMddHH24missSSS')||rownum,a.roleid,c.menuid" +
                        " from t_sys_role_menu a inner join t_sys_menu b on a.menuid=b.menuid" +
                        " inner join t_sys_menu c on c.bizcode=b.bizcode and c.oldbelongtoapp=b.belongtoapp " +
                        " where c.belongtoapp=? and a.menuid in ('" + menuids.replaceAll(",", "','") + "')",
                ConfigUtil.getString("portalCode")
        );
    }

    public void saveOrUpdate(Object myaction) throws Exception {
        //清除资源树缓存数据
        CacheUtils.delete("ZYTreeJsonData");
        String []  serviceids=null;

        IdMenuAction action = (IdMenuAction) myaction;
        TSysMenu menu = action.getTsysMenu();

        if (null == menu) {

            action.addActionError("保存失败[ 被保存的对象为null ]");
        } else {
//            //上海工会乱码问题
//            if (Constants.ProjectInfo.CHARACTER_SET_SWITCH.equals("true")) {
//                if (StringUtil.isNotBlank(menu.getMenuname())) {
//                    menu.setMenuname(new String(menu.getMenuname().getBytes("8859_1"), "UTF-8"));
//                }
//            }
            if (StringUtil.isBlank(menu.getMenuid())) {

                String newMenuid = getNewMenuIdByParentMenuId(menu.getUpmenuid());
                menu.setMenuid(newMenuid);

                menu.setDepth((short) (newMenuid.length() / 3));
                if (menu.getState() == null || menu.getState().equals("")) {
                    menu.setState("1");
                }
                if (StringUtil.isBlank(menu.getBizcode())) {
                    menu.setBizcode(newMenuid);
                }
                getBaseDao().save(menu);

                BusinessLogUtil.log(action.getLoginuser().getUserloginid(), SysConstant.CZDX_T_SYS_MENU,
                        SysConstant.LOG_ACTION_SAVE, IdLoginAction.getIpAddr(action.getRequest()));
            } else {

                getBaseDao().update(menu);
                if ("0".equals(menu.getState())) {//禁用本级菜单，自动禁用其所有子菜单。否则角色菜单树加载会错乱。
                    String hql = "update TSysMenu set state=0 where upmenuid = ?";
                    getBaseDao().executeHql(hql, menu.getMenuid());
                }

                BusinessLogUtil.log(action.getLoginuser().getUserloginid(), SysConstant.CZDX_T_SYS_MENU,
                        SysConstant.LOG_ACTION_UPDATE, IdLoginAction.getIpAddr(action.getRequest()));
            }
            action.setParameter("refresh", true);
        }

//        //图标库集合
//        List<String> listIcon = new ArrayList<String>();
////      File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator + "images" + File.separator + "shd" + File.separator + "icons");
////        File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator +  "images" + File.separator + "shd"+ File.separator + "newicons");
////        for (File f : file.listFiles()) {
////            listIcon.add(f.getName());
////            imgeMap.put(f.getName(), f.getName());
////        }
//        File file = new File(action.getSession().getServletContext().getRealPath("/") + File.separator + "resources" + File.separator + "images" + File.separator + "shd" + File.separator + "icons");
//        for (File f : file.listFiles()) {
//            if (imgeMap.get(f.getName())==null){
//                listIcon.add(f.getName());
//            }
//        }
//        action.setListIcon(listIcon);
//
//        //山大增加菜单服务扩展信息与服务列表设置
//        if (true||Constants.ProjectInfo.PROJECT_CODE.equals("shd")) {
//            TServiceIntroducd tserviceintroducd = action.getTserviceintroducd();
//            String serviceid = action.getServiceid();
//            if (StringUtil.isNotBlank(serviceid)) {
//                serviceid = serviceid.replace(" ", "");
//                serviceids = serviceid.split(",");
//            }
//
//            String del_introducd=" delete from T_Service_Introducd t where t.menuid =?";
//            try {
//                DBUtil.executeSQL(del_introducd, menu.getMenuid());// 删除原数据描述信息
//            }catch (Exception e){
//                e.printStackTrace();
//                throw new RuntimeException(e); // 抛出的异常都是致命异常，否则都已经捕捉后处理了
//            }
//            tserviceintroducd.setWid(SeqFactory.getNewSequenceAlone());
//            tserviceintroducd.setTitle(menu.getMenuname());
//            tserviceintroducd.setMenuid(menu.getMenuid());
//            tserviceintroducd.setCjrq(new Date());
//            tserviceintroducd.setCjr(action.getLoginuser().getUserloginid());
//            getBaseDao().save(tserviceintroducd);
//            TServiceMenu tserviceMenu =new TServiceMenu();
//            try {
//                DBUtil.executeSQL("delete from t_service_Menu where menuid=?", menu.getMenuid());// 删除原类别
//            }catch (Exception e){
//                e.printStackTrace();
//                throw new RuntimeException(e); // 抛出的异常都是致命异常，否则都已经捕捉后处理了
//            }
//            if (serviceids!=null&&serviceids.length>0){
//                for (int j=0;j<serviceids.length;j++) {
//                    tserviceMenu = new TServiceMenu();
//                    tserviceMenu.setWid(SeqFactory.getNewSequenceAlone());
//                    tserviceMenu.setMenuid(menu.getMenuid());
//                    tserviceMenu.setServiceid(serviceids[j]);
//                    getBaseDao().save(tserviceMenu);
//                }
//            }
//
            //装载服务类别
            loadService(action, menu.getMenuid());
            loadServicedescribe(action, menu.getMenuid());
//            action.setServices(serviceid);
//            action.setTserviceintroducd(tserviceintroducd);
//        }
    }

    /**
     * 生成新的ID号 规则：根据父ID查询其下一级最大的ID号，然后增加一。
     *
     * @param parentid
     * @return 新的ID号
     * @throws Exception
     */
    private static String getNewMenuIdByParentMenuId(String parentid) throws Exception {

        return SeqFactory.getNewTreeIdByParentId("T_Sys_Menu", "menuid", "upMenuId", parentid);
    }

    /**
     * 复制一个节点 到指定节点下
     *
     * @param tsysMenu 包含了被复制节点的menuid和目标节点id(upmenuid)
     * @return
     * @throws Exception
     */
    public String copyNode(TSysMenu tsysMenu) throws Exception {
        copyOneNode(tsysMenu);
        return "ok";
    }

    private TSysMenu copyOneNode(TSysMenu tsysMenu) throws Exception {
        String newParentNodeId = tsysMenu.getUpmenuid();//新的父节点
//        tsysMenu = baseDao.findById(TSysMenu.class, tsysMenu.getMenuid());// 填充URL等字段
        tsysMenu = DBUtil.queryBean("select * from t_sys_menu where menuid=?", TSysMenu.class, tsysMenu.getMenuid());
        tsysMenu.setUpmenuid(newParentNodeId);// 重新设置新的父节点值
        String myNewNodeId = getNewMenuIdByParentMenuId(newParentNodeId);
        tsysMenu.setMenuid(myNewNodeId);
        baseDao.save(tsysMenu);
        return tsysMenu;
    }

    /**
     * 移动节点。和原菜单的关联都将被更新成新菜单
     *
     * @param tsysMenu
     * @return
     * @throws Exception
     */
    public String moveNodeBySTA(TSysMenu tsysMenu) throws Exception {
        String menuid = tsysMenu.getMenuid();
        long sons = baseDao.count("select count(*) from TSysMenu where upmenuid = ?", menuid);
        if (sons > 0) {
            return "不能移动有子节点的节点";
        }
        String newMenuId = copyOneNode(tsysMenu).getMenuid();

        DBUtil.executeSQL("update t_sys_user_menu set menuid=? where menuid=?", newMenuId, menuid);
        DBUtil.executeSQL("update t_sys_role_menu set menuid=? where menuid=?", newMenuId, menuid);
        DBUtil.executeSQL("update t_sys_role_menu_button set menuid=? where menuid=?", newMenuId, menuid);
        DBUtil.executeSQL("update t_fw_dy set menuid=? where menuid=?", newMenuId, menuid); //修改关联的服务资源订阅
        DBUtil.executeSQL("delete from t_sys_menu where menuid=?", menuid);// 删除原菜单
//        getBaseDao().deleteAll("TSysMenu", "menuid", "=", menuid);// 删除原菜单
        return "ok";
    }

    /**
     * 拼接id
     *
     * @param id
     * @return
     */
    public String joinId(String id, int j) {
        String pre = id.substring(0, id.length() - 3);
        id = id.substring(id.length() - 3);
        id = String.valueOf(Integer.parseInt(id) + j);
        if (id.length() >= 3) {
            return pre + id;
        } else if (id.length() == 2) {
            return pre + "0" + id;
        }
        return pre + "00" + id;
    }

    /**
     * 加载业务服务分类信息
     * @param action
     * @param menuid
     */
    private void loadService(IdMenuAction action,String menuid){
        TServiceCodesort tservicecodesort=null;
        TServiceMenu tserviceMenu=null;
        StringBuffer sb_mene=new StringBuffer();
        String sqlCodesort="select * from t_service_codesort t ";
        String sqlCode="select * from t_service_code t where t.zdlb=? and t.sfsy='1'";
        String sqlmemu="select * from t_service_menu t where t.menuid=? ";
        List<TServiceCodesort> tservicecodesortList = DBUtil.queryAllBeanList(sqlCodesort, TServiceCodesort.class);
        if (tservicecodesortList!=null&&tservicecodesortList.size()>0){
            for (int i=0;i<tservicecodesortList.size();i++){
                tservicecodesort=tservicecodesortList.get(i);
                List<TServiceCode> tservicecodeList = DBUtil.queryAllBeanList(sqlCode, TServiceCode.class,tservicecodesort.getZdlb());
                tservicecodesort.setTservicecodeList(tservicecodeList);
            }
        }
        action.setTservicecodesortList(tservicecodesortList);
        List<TServiceMenu> tserviceMenusList = DBUtil.queryAllBeanList(sqlmemu, TServiceMenu.class,menuid);
        if (tserviceMenusList!=null&&tserviceMenusList.size()>0){
            for (int i=0;i<tserviceMenusList.size();i++){
                tserviceMenu =tserviceMenusList.get(i);
                sb_mene.append(tserviceMenu.getServiceid()+",");
            }
            sb_mene.deleteCharAt(sb_mene.length()-1);
        }
        action.setServices(sb_mene.toString());
    }

    /**
     * 加载业务服务描述信息
     * @param action
     * @param menuid
     */
    private void loadServicedescribe(IdMenuAction action,String menuid){
        TServiceCodesort tservicecodesort=null;
        TServiceMenu tserviceMenu=null;
        StringBuffer sb_mene=new StringBuffer();
        String sql=" select * " +
                   " from t_service_introducd t " +
                   " where t.menuid =? ";
        List<TServiceIntroducd> tserviceintroducdList = DBUtil.queryAllBeanList(sql, TServiceIntroducd.class,menuid);
       if (tserviceintroducdList != null && tserviceintroducdList.size() > 0){
           action.setTserviceintroducd(tserviceintroducdList.get(0));
       }
    }
}
